package com.zwh.controller;

import com.zwh.entity.User;
import com.zwh.service.UserService;
import com.zwh.utils.VerifyCodeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("user")
public class UsreController {

    private static final Logger log = LoggerFactory.getLogger(UsreController.class);
    private UserService userService;

    @Autowired
    public UsreController(UserService userService) {
        this.userService = userService;
    }

    //安全退出
    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/login";//退出后回到登录界面就行
    }

    //用户登录
    @RequestMapping("login")
    public String login(String username,String password,HttpSession session){
        try {
            //调用业务层进行登录
            User user = userService.login(username, password);
            //保存用户信息
            session.setAttribute("user",user);
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/login";//登录失败跳回到登录界面
        }
        return "redirect:/employee/lists";//登录成功后，跳转到查询所有员工信息控制器路径
    }


    @RequestMapping("regist")
    public String regist(User user, String code, HttpSession session) {
        try {
            // 判断用户输入的验证码和 session 中的验证码是否一致
            Object sessionCodeObj = session.getAttribute("code");
            if (sessionCodeObj == null) {
                throw new RuntimeException("验证码已过期，请重新获取");
            }
            String sessionCode = sessionCodeObj.toString();
            if (!sessionCode.equalsIgnoreCase(code)) {
                throw new RuntimeException("验证码输入错误");
            }
            // 注册用户
            userService.regist(user);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return "redirect:/regist";
        }

        return "redirect:/login";
    }

    // 生成验证码
    @RequestMapping("generateImageCode")
    public void generateImageCode(HttpSession session, HttpServletResponse response) throws IOException {
        // 生成 4 位随机数
        String code = VerifyCodeUtils.generateVerifyCode(4);
        // 保存 session 作用域
        session.setAttribute("code", code);
        // 根据随机数生成图片
        response.setContentType("image/png");
        ServletOutputStream os = response.getOutputStream();
        VerifyCodeUtils.outputImage(220, 60, os, code);
    }
}